import React, { useState, useRef, useEffect, useMemo } from 'react';
import layout from '../common/layout';
import {
  Button,
  Form,
  Input,
  Row,
  Col,
  Tag,
  Select,
  DatePicker,
  message,
  Spin,
} from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import {
  deptListApi,
  userInfoApi,
  userPhotoApi,
  userSaveApi,
} from '../../apis/userApi';
import { USER_INFO } from '../../config/common.config';

function Edit({ location, match }) {
  const [fileName, setFileName] = useState([]);
  const imgNode = useRef();
  const { Option } = Select;
  const [user, setUser] = useState(USER_INFO);
  const [deptList, setDeptList] = useState([]);
  const [formNode] = Form.useForm();
  const [isEdit, setIsEdit] = useState(false);
  const [pageLoading, setPageLoading] = useState(true);
  const canvasRef = useRef(null);
  useEffect(() => {
    const fetchData = async () => {
      let result = await deptListApi();
      if (result.code === 200) {
        setDeptList(result.data);
      }
      let id = location.state?.id || '';
      console.log(location);
      setIsEdit(!!id);
      if (id) {
        let currentUser = await userInfoApi(id);
        if (currentUser.code === 200) {
          console.log(currentUser);
          let _user = {};
          let _data = currentUser.data;
          for (let name in user) {
            if (name === 'birthday') {
              _user[name] = _data[name]
                ? dayjs(_data[name]).format('YYYY-MM-DD')
                : null;
            } else {
              _user[name] = _data[name] || '';
            }
          }
          setUser(_user);
          formNode.setFieldsValue({
            ..._user,
            birthday: _user.birthday ? dayjs(_user.birthday) : null,
          });
        }
      }
      setPageLoading(false);
    };

    fetchData();
  }, []); // 缺少 user 和 formNode 依赖项

  const dutiesList = useMemo(() => {
    return (deptList.find((it) => it.name === user.dept) || {}).children || [];
  }, [user.dept]);

  function fileUploadEvt() {
    console.log('进来了');
    let input = document.createElement('input');
    input.setAttribute('type', 'file');
    input.setAttribute('accept', 'image/*');

    input.onchange = function () {
      console.log(this.files);
      const file = this.files[0];
      if (!file) return;

      // 检查文件类型
      if (!file.type.startsWith('image/')) {
        message.error('请上传图片文件');
        return;
      }

      // 检查文件大小(如:2MB)
      if (file.size > 2 * 1024 * 1024) {
        message.error('图片大小不能超过2MB');
        return;
      }

      fileBase64canvas(file);
      fileUpload([file]);
    };
    input.click();
  }

  // 修改 fileBase64Upload 函数, 并使用 canvas 进行图片裁剪预览
  function fileBase64canvas(file) {
    let reader = new FileReader();
    reader.onload = function () {
      let image = new Image();
      image.onload = function () {
        const canvas = canvasRef.current;
        const ctx = canvas.getContext('2d');
        ctx.drawImage(image, 0, 0, image.width, image.height, 0, 0, 64, 64);
        let base64 = canvas.toDataURL();
        imgNode.current.src = base64;
      };
      image.src = reader.result;
    };
    reader.readAsDataURL(file);
  }

  async function fileUpload(files) {
    let fd = new FormData();
    for (let file of files) {
      // Blob --> 表示大二进制对象
      fd.append('fileName', file);
      // 以前文件上传或者下载需要获取进度，只能是一个伪进度
      //3、现在可以使用 Ajax.onprogress方法  +  FormData数据可以获取实时数据
      let result = await userPhotoApi(fd, (progressEvent) => {
        const progress = Math.round(
          (progressEvent.loaded / progressEvent.total) * 100
        );
        message.loading({
          content: `上传进度：${progress}%`,
          key: 'uploadProgress',
          duration: 0,
        });

        if (progress === 100) {
          message.success({
            content: '上传完成',
            key: 'uploadProgress',
          });
        }
      });
      console.log('上传响应结果：', result); // 添加这行来检查响应
      if (result.code === 200) {
        // 确保 result.data[0].path 包含完整的图片URL
        const photoUrl = result.data[0].path.startsWith('http')
          ? result.data[0].path
          : 'http://www.localhost:20000' + result.data[0].path;

        setUser({
          ...user,
          photo: photoUrl,
        });

        formNode.setFieldsValue({
          photo: photoUrl,
        });
      }
    }
  }

  async function submitEvt() {
      try {
        // 表单验证
        await formNode.validateFields();
        // 保存用户信息
        const result = await userSaveApi(user);
        if (result.code === 200) {
          message.success('保存用户成功');
          // 保存成功后返回上一页
          window.history.back();
        } else {
          message.error(result.msg || '保存失败，请重试');
        }
      } catch (error) {
        console.error('保存用户失败:', error);
        message.error('表单验证失败或保存出错，请检查输入');
      }
    }

  // 添加下载图片的函数
  function downloadImage() {
    if (!user.photo) {
      message.warning('没有可下载的图片');
      return;
    }
    try {
      // 创建一个临时的a标签用于下载
      const link = document.createElement('a');
      // 处理图片URL，确保使用完整路径
      const imageUrl = user.photo.startsWith('http')
        ? user.photo
        : `http://www.localhost:20000${user.photo}`;
      link.href = imageUrl;
      //不需要设置 target="_blank" ，因为这是下载操作而不是打开新窗口
      // 设置下载文件名
      // 确保文件名中包含用户ID或其他唯一标识符
      link.download = `用户头像_${user.id || '未命名'}.png`;
      // 将a标签添加到文档中并触发点击事件
      // 触发下载
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    } catch (error) {
      console.error('下载图片失败:', error);
      message.error('下载图片失败，请稍后重试');
    }
  }

  return (
    <Spin
      wrapperClassName="layout-loading"
      spinning={pageLoading}
      tip="Loading"
    >
      <div className="page-layout no-footer">
        <header>
          <Button type="primary" onClick={submitEvt}>
            保存
          </Button>
          <Button onClick={() => window.history.back()}>返回</Button>
        </header>
        <article>
          {/* LabelCol是设置每一个表单项的Label样式属性 */}
          <Form form={formNode} labelCol={{ style: { width: '110px' } }}>
            <Row>
              {/* 一行24列，xs全部占了，只放一个 */}
              <Col
                xs={{ span: 24 }}
                md={{ span: 12 }}
                lg={{ span: 8 }}
                xl={{ span: 6 }}
              >
                <Form.Item
                  label="用户编码"
                  name="id"
                  rules={[{ required: true, message: '请输入用户编码!' }]}
                >
                  <Input
                    value={user.id}
                    onChange={(evt) => {
                      setUser({
                        ...user,

                        id: evt.target.value,
                      });
                    }}
                  />
                </Form.Item>
              </Col>
              <Col
                xs={{ span: 24 }}
                md={{ span: 12 }}
                lg={{ span: 8 }}
                xl={{ span: 6 }}
              >
                <Form.Item
                  label="用户姓名"
                  name="username" // 表单字段名为 username
                  rules={[{ required: true, message: '请输入用户姓名' }]}
                >
                  <Input
                    value={user.name} // 但状态中使用的是 name
                    onChange={(evt) => {
                      setUser({
                        ...user,
                        name: evt.target.value, // 这里也是 name
                      });
                    }}
                  />
                </Form.Item>
              </Col>
              <Col
                xs={{ span: 24 }}
                md={{ span: 12 }}
                lg={{ span: 8 }}
                xl={{ span: 6 }}
              >
                <Form.Item
                  label="用户密码"
                  name="password"
                  rules={[
                    { required: true, message: '请输入用户密码' },
                    { min: 6, message: '密码长度不能小于6位' },
                    {
                      pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{6,20}$/,
                      message: '密码必须包含大小写字母和数字',
                    },
                  ]}
                >
                  <Input // 应该使用 Input.Password
                    value={user.password}
                    onChange={(evt) => {
                      setUser({
                        ...user,

                        password: evt.target.value,
                      });
                    }}
                  />
                </Form.Item>
              </Col>
              <Col
                xs={{ span: 24 }}
                md={{ span: 12 }}
                lg={{ span: 8 }}
                xl={{ span: 6 }}
              >
                <Form.Item label="用户头像" name="photo">
                  <Input.Search
                    placeholder="请选择图片"
                    readOnly
                    value={user.photo}
                    enterButton={<UploadOutlined onClick={fileUploadEvt} />}
                  />
                </Form.Item>
              </Col>
              <Col
                xs={{ span: 24 }}
                md={{ span: 12 }}
                lg={{ span: 8 }}
                xl={{ span: 6 }}
              >
                <Form.Item label="用户性别" name="sex">
                  <Select
                    value={user.sex}
                    onChange={(val) => {
                      setUser({
                        ...user,

                        sex: val,
                      });
                    }}
                  >
                    <Option value="男">男</Option>
                    <Option value="女">女</Option>
                    <Option value="未知">未知</Option>
                  </Select>
                </Form.Item>
              </Col>
              <Col
                xs={{ span: 24 }}
                md={{ span: 12 }}
                lg={{ span: 8 }}
                xl={{ span: 6 }}
              >
                <Form.Item label="用户生日" name="birthday">
                  <DatePicker
                    value={user.birthday ? dayjs(user.birthday) : null}
                    onChange={(_date) => {
                      setUser({
                        ...user,
                        birthday: _date ? _date.format('YYYY-MM-DD') : null,
                      });
                    }}
                    format="YYYY-MM-DD"
                  />
                </Form.Item>
              </Col>
              <Col
                xs={{ span: 24 }}
                md={{ span: 12 }}
                lg={{ span: 8 }}
                xl={{ span: 6 }}
              >
                <Form.Item label="用户部门" name="dept">
                  <Select
                    value={user.dept}
                    onChange={(val) => {
                      setUser({
                        ...user,
                        dept: val,
                      });
                    }}
                  >
                    {deptList.map((it) => {
                      return (
                        <Option value={it.name} key={it.name}>
                          {it.name}
                        </Option>
                      );
                    })}
                  </Select>
                </Form.Item>
              </Col>
              <Col
                xs={{ span: 24 }}
                md={{ span: 12 }}
                lg={{ span: 8 }}
                xl={{ span: 6 }}
              >
                <Form.Item label="用户职位" name="duties">
                  <Select
                    value={user.duties}
                    onChange={(val) => {
                      setUser({
                        ...user,
                        duties: val,
                      });
                    }}
                  >
                    {/* <Option value="男">男</Option>
                          <Option value="女">女</Option>
                          <Option value="未知">未知</Option> */}

                    {dutiesList.map((it) => {
                      return (
                        <Option value={it} key={it}>
                          {it}
                        </Option>
                      );
                    })}
                  </Select>
                </Form.Item>
              </Col>
            </Row>
          </Form>

          <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
            <img
              src={user.photo}
              alt="用户头像"
              ref={imgNode}
              style={{
                maxWidth: '100px',
                display: user.photo ? 'block' : 'none',
              }}
            />
            {user.photo && (
              <Button
                icon={<UploadOutlined />}
                onClick={downloadImage}
                type="link"
              >
                下载头像
              </Button>
            )}
          </div>

          <hr />
          <canvas ref={canvasRef} width="64" height="64" />
        </article>
      </div>
    </Spin>
  );
}

export default layout(Edit);
